package tree.binarysearchtree;

public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;

    public void insert(int val) {
        if (root == null) {
            root = new TreeNode(val);
            return;
        }
        TreeNode parent = root;
        TreeNode cur = root;
        TreeNode newNode = new TreeNode(val);
        while (cur != null) {
            parent = cur;
            if (cur.val < val) {
                cur = cur.right;
            } else if (cur.val > val) {
                cur = cur.left;
            } else {
                return;
            }
        }
        if (parent.val > val) {
            parent.left = newNode;
        } else {
            parent.right = newNode;
        }
    }

    public TreeNode search(int val) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur.val < val) {
                cur = cur.right;
            } else if (cur.val > val) {
                cur = cur.left;
            } else {
                return cur;
            }
        }
        return null;
    }

    public void remove(int val) {
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            parent = cur;
            if (cur.val < val) {
                cur = cur.right;
            } else if (cur.val > val) {
                cur = cur.left;
            } else {
                remove(parent, cur);
            }
        }
    }

    public void remove(TreeNode parent, TreeNode cur) {
        if (cur.left == null) {
            if (cur == root) {
                root = cur.right;
            } else if (parent.left == cur) {
                parent.left = cur.right;
            } else {
                parent.right = cur.right;
            }
        } else if (cur.right == null) {
            if (cur == root) {
                root = cur.left;
            } else if (parent.left == cur) {
                parent.left = cur.left;
            } else {
                parent.right = cur.left;
            }
        } else {
            TreeNode minNodeParent = cur;
            TreeNode minNode = cur.right;
            while (minNode.left != null) {
                minNodeParent = minNode;
                minNode = minNode.left;
            }
            cur.val = minNode.val;
            if (minNodeParent.left == minNode) {
                minNodeParent.left = minNode.right;
            } else {
                minNodeParent.right = minNode.right;
            }
        }
    }
}
